import styles from "./index.module.less";
import { Button, Card } from "antd";
import { useState, useEffect } from "react";
import axios from "@/api";

// 上传文件
const uploadFile = (formData) => {
  axios
    .post(
      "/minor/uploadFile",
      formData,
      {
        header: {
          Accept: "multipart/form-data",
        },
      },
      {
        onUploadProgress() {
          console.log("progress");
        },
      }
    )
    .then((resp) => {
      console.log("响应数据", resp);
    });
};

// 分块
function createChunk(file, chunkSize) {
  const result = [];
  for (let i = 0; i < file.size; i += chunkSize) {
    result.push(file.slice(i, i + chunkSize));
  }
  return result;
}

// 并发控制
async function concurrency(ps, limt = 3) {
  const taskPool = new Set();
  const type = Object.prototype.toString.call(ps);
  if (type == "[object Array]") {
    for (const task of ps) {
      const promise = Promise.resolve(task());
      taskPool.add(promise);
      promise.then((e) => {
        taskPool.delete(promise);
      });
      if (taskPool.size >= limt) {
        await Promise.race(taskPool);
      }
    }
    return Promise.allSettled(taskPool);
  } else {
    return Promise.reject("不是数组");
  }
}

export default function FileUpload() {
  const [file, setFile] = useState(null);
  const [testFile, setTestFile] = useState([]);

  const handInputFile = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.onchange = function (e) {
      const file = e.target.files[0];

      setFile(file);
      setTestFile([...testFile, file]);
    };
    input.click();
  };

  // 上传文件
  const handUploadFile = () => {
    if (!file) {
      throw "还未上传文件";
    }
    const taskQueue = [];
    const chunkSize = 50 * 1024 * 1024; // 每个切块的大小，这里设置为1MB
    const totalChunks = Math.ceil(file.size / chunkSize); // 总共切成多少块
    const chunkFile = createChunk(file, chunkSize); //文件切片
    // 每个块都创建 formData 生成请求队列数组
    console.log(file.name);
    chunkFile.forEach((chunk, index) => {
      const formData = new FormData();
      formData.append("file", chunk);
      formData.append("fileName", file.name);
      formData.append("totalChunks", totalChunks);
      formData.append("chunkSize", chunkSize);
      taskQueue.push(() => {
        return uploadFile(formData);
      });
    });
    // 准备控制并发请求 上传数据块
    // concurrency(taskQueue);
    const allFile = new FormData()
    allFile.append("file",file)
    allFile.append("fileName", file.name);
    uploadFile(allFile) 
  };

  // 测试按钮一号
  const handTestOne = () => {
    console.log(styles);
    console.log(file);
  };

  return (
    <div className={styles.showline}>
      <div className={styles.testView}>
        <h2>测试</h2>
        <div>
          <Button onClick={handTestOne}>点击测试一</Button>
        </div>
      </div>
      <h1 className={styles.handlerBtn}>
        <Button onClick={handInputFile}>点击上传文件</Button>
        <Button onClick={handUploadFile}>点击调用接口</Button>
      </h1>
      <div className={styles.fileList}>
        <h2>测试文件上传列表</h2>
        <div className={styles.testFile}>
          {testFile.map((e, index) => {
            return (
              <p key={index} className={styles.file}>
                {e.name}
              </p>
            );
          })}
        </div>
        {/* <h2>上传文件列表</h2>
        <Card className={styles.serveFile}></Card> */}
      </div>
    </div>
  );
}
